//入口函数
$NG.AllReady(
    function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange, useBeforeClick }) {
      //获取容器数据和表单数据
      var mstform = $NG.getCmpApi("p_form_zbhy"); //获取表头数据
      var BD = $NG.getCmpApi("p_form_section"); //获取表体数据 标段
      var WLMX = $NG.getCmpApi("p_form_wlmx"); //获取表体数据 物料明细
      var YQGYS = $NG.getCmpApi("p_form_supply"); //获取表体数据 邀请供应商
      var PBZB = $NG.getCmpApi("p_form_pbzb"); //获取表体数据 评标指标
      var ZBWJ = $NG.getCmpApi("p_form_zbwj"); //获取表体数据 招标文件
      var toolbar = $NG.getCmpApi("toolbar_top");
      var tabPanel = document.getElementsByClassName("ant-tabs-tab"); //获取所有tab页元素
      var YQGYSdtoolbar1 = $NG.getCmpApi("toolbar_p_form_supply");
      $NG.getCmpApi("toolbar_p_form_zbwj").getItem("import").setHidden();
      $NG.getCmpApi("toolbar_p_form_pbzb").getItem("import").setHidden();
      $NG.getCmpApi("toolbar_p_form_zbwj").getItem("attachment").setHidden();
      $NG.getCmpApi("toolbar_p_form_pbzb").getItem("attachment").setHidden();
      $NG.getCmpApi("toolbar_p_form_wlmx").getItem("attachment").setHidden();
      const storedData = localStorage.getItem("selectedUSourceData");
      const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_wlmx");

      function getCookie(name) {
        let cookieArray = document.cookie.split('; ');
        for (let i = 0; i < cookieArray.length; i++) {
            let [cookieName, cookieValue] = cookieArray[i].split('=');
            if (cookieName === name) {
                return decodeURIComponent(cookieValue);
            }
        }
        return null;
    }
    
      toolbar.insert({
        id: "toZbgg",
        text: "跳转招标公告",
        iconCls: "icon-InsertRow",
      });
      useClick(()=>{
        const phid = mstform.getItem("u_gg_phid").getValue()
        if(phid){
            //读取token
            const token = getCookie("i86.1P2tokenkey")
            $NG.open(`http://nginx.clouddev.hisense.com/PMS/CRM/CntTenderBulletin/CntTenderBulletinEdit?otype=view&id=${phid}&Authorization=${token}&AppTitle=%E6%8B%9B%E6%A0%87%E5%85%AC%E5%91%8A-%E6%9F%A5%E7%9C%8B`)
        }
        else{
            $NG.alert("请审核通过自动生成招标公告后点击！")
        }
      })
      if (toolbar_dgrid) {
        toolbar_dgrid.insert({
          id: "template_download",
          text: "模板下载",
          iconCls: "icon-InsertRow",
        });
        // 增加匹配物料
        toolbar_dgrid.insert({
          id: "user_match",
          text: "匹配物料",
          iconCls: "icon-InsertRow",
        });
        toolbar_dgrid.insert({
          id: "get_price",
          text: "获取价格库结果",
          iconCls: "icon-InsertRow",
        });
        useClick(async function ({ args }) {
          const url = "http://nginx.clouddev.hisense.com/report/index.html#/tableDesign/TableManager/preview?AppTitle=%E6%8A%A5%E8%A1%A8%E9%A2%84%E8%A7%88&defaultSheet=0&name=%E5%AE%9A%E4%BB%B7%E6%96%B9%E6%A1%88%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF&menucode=968d9a45-9772-46b9-9c6c-f3d9e56a6676";
          // 打开报表并传递参数
          $NG.open(url, { AppTitle: "报表查看" });
        }, "template_download");
      }
      useClick(async function ({ args }) {
        let rows = WLMX.getRows();
        console.log(rows);
        const checkedCount = rows.filter((item) => item.checked === true).length;
        const price = WLMX.getSelectedRow().u_item_no;
        // 验证逻辑
        if (checkedCount !== 1 || price == "") {
          // 提示错误（根据实际需求选择提示方式）
          $NG.alert("请选择且只能选择一条数据！"); // 弹窗提示
          return 0; // 或者返回错误代码
        } else {
          // 验证通过继续后续操作
          $NG.external
            .openNGHelp({
              type: "NGMultipleHelp",
              helpId: "prc_k",
              valueField: "phid_itemdata",
              labelField: "item_name",
              clientSqlFilter: "phid_itemdata = " + price,
            })
            .then((data) => {
              if (data.length > 1) {
                $NG.alert("请选择其中一条数据，不可多选！");
                return;
              } else {
                const newDataSource = rows.map((row) => {
                  // 只处理被选中的行
                  if (row.checked) {
                    return {
                      ...row, // 保留其他字段
                      u_zbprc: data[0].origin.wsprc,
                      u_zbprcvat: data[0].origin.hsprc,
                      u_zbrate: data[0].origin.taxrate,
                    };
                  }
                  return row; // 未选中的行保持原样
                });
                // WLMX.getSelectedRow().u_zbprc = data[0].origin.wsprc;
                // WLMX.getSelectedRow().u_zbprcvat = data[0].origin.hsprc;
                // WLMX.getSelectedRow().u_zbrate = data[0].origin.taxrate;
                console.log(data, newDataSource);
                WLMX.clearRows().then(() => {
                  WLMX.addRows(newDataSource);
                });
  
                WLMX.refreshView();
              }
            });
  
          console.log("验证通过");
          return 1; // 或者返回成功代码
        }
      }, "get_price");
  
      mstform.getItem("u_skdw").setValue({
        value: 8570000000000018,
        label: "青岛海信网络科技股份有限公司",
      });
  
      useValuesChange(({ args }) => {
        // console.log(`fg3_unitaccount.phid_ent = '${mstform.getItem("u_skdw")?.getValue() || ""}'`);
        console.log(args[0].u_skdw.origin.OrgId);
        
        khBank(args[0].u_skdw.origin.OrgId);
      }, "p_form_zbhy.u_skdw");
      useValuesChange(({ args }) => {
        // console.log(`fg3_unitaccount.phid_ent = '${mstform.getItem("u_skdw")?.getValue() || ""}'`);
        console.log(args);
        mstform.getItem('u_bank_name').setValue(args[0].u_kh_bank.origin.accountname)
        mstform.getItem('u_account').setValue(args[0].u_kh_bank.origin.accountno)
  
      }, "p_form_zbhy.u_kh_bank");
      khBank(8570000000000014);
      function khBank(params) {
        console.log(params);
        
        if (!mstform.getItem("u_skdw")) return;
        var u_skdw = mstform.getItem("u_skdw").getValue() || "";
        console.log("u_skdw_filter");
        // console.log(u_skdw);
  
        $NG.updateUI((updater) => {
          const fields = ["u_kh_bank"];
          fields.forEach((field) => {
            // $NG.getPageUI();
            // 根据组件目录设置路径，可能存在
            // fieldSetForm
            // PCFieldSetPanelGroup[i][field]
            updater.fieldSetForm.p_form_zbhy.PCFieldSetPanelGroup3[field].setProps({
              // hidden: true, //隐藏
              // required: true, //必输
              // disabled: true, //只
              clientSqlFilter: `fc3_outer_acc_mst.phid_open_org ='${params}'`, //过滤条件
  
              // placeholder: "请选择", //输入框字段加提示语
              // data: [{ value: "01", label: "实施外包用工" }], //下拉过滤
            });
          });
        });
      }
      
      const checkBiaoshiInUrl = () => {
        const hash = window.location.hash.substring(1);
        const [path, query] = hash.split("?");
        if (query) {
          const urlParams = new URLSearchParams(query);
          return urlParams.has("biaoshi");
        }
  
        return false;
      };
  
      // 调用检测
      if (checkBiaoshiInUrl()) {
        console.log("URL 中包含 biaoshi 字段");
        $NG.updateUI((updater) => {
          const fields = ["u_kz_prcvat", "u_kz_tax", "u_kz_amtvat", "u_ck_prcvat", "u_ck_amtvat"];
          fields.forEach((field) => {
            updater.editGrid.p_form_wlmx[field].setProps({
              disabled: false,
            });
          });
        });
        $NG.updateUI((updater) => {
          const fields = ["u_item_no", "u_item_name", "u_unit", "u_ncg_qty", "u_spec", "u_sj_spec", "itemno", "itemname", "msunit", "spec", "u_wlfl", "u_zbqty", "u_yztj_prc", "u_zbprc", "u_zbprcvat", "u_zbrate", "u_zbamtvat", "u_zbamt", "u_remarks", "u_source_table", "u_source_id"];
          fields.forEach((field) => {
            updater.editGrid.p_form_wlmx[field].setProps({
              disabled: true,
            });
          });
        });
        $NG.updateUI((updater) => {
          const fields = ["u_ncg_qty", "u_yztj_prc"];
          fields.forEach((field) => {
            updater.editGrid.p_form_wlmx[field].setProps({
              disabled: true,
            });
          });
        });
        const hash = window.location.hash.substring(1);
        const [path, query] = hash.split("?");
        if (query) {
          const urlParams = new URLSearchParams(query);
          urlParams.delete("biaoshi");
          const newHash = path + (urlParams.toString() ? `?${urlParams.toString()}` : "");
          window.history.replaceState({}, "", window.location.pathname + "#" + newHash);
        }
      }
      if (storedData) {
        const parsedData = JSON.parse(storedData);
        // 获取行数
        console.log(parsedData);
        mstform.getItem('u_kbfzr').setValue({
            value:parsedData[0].u_director_phid,
            label:parsedData[0].u_director_phid_EXName
        }) 
  
        const gridCount = parsedData.length;
  
        let gridArr = []; // 初始化数组
  
        // 将 execServer 封装为 Promise
        function fetchData(item) {
  
          return new Promise((resolve, reject) => {
            $NG.execServer("getDjxqcByPhid", { phid: item.u_source_id, resource_table: `'${item.u_source_table}'` }, function (res) {
              try {
                console.log("进入功能扩展getDjxqcByPhid1");
                if (res.count > 0) {
                  const data = JSON.parse(res.data)[0].extendObjects;
                  console.log(data);
                  let gridObj = {
                    u_source_id: data.source_id,
                    u_source_table: data.source_table,
                    itemid: data.ps_resbase_phid,
                    u_item_no: data.item_phid,
                    u_item_no_EXName: data.item_no,
                    u_item_name: data.item_name,
                    u_unit: data.unit_phid,
                    u_unit_EXName: data.unit_name,
                    u_spec: data.spec,
                    u_sj_spec: data.spec,
                    u_wlfl: data.resbs_phid,
                    u_wlfl_EXName: data.resbs_name,
                    u_ncg_qty: data.u_qty,
                    u_yztj_prc: data.u_vat_prc,
                    u_pnum:data.u_sj_no,
                    u_pname:data.u_sj_name
                  };
  
                  resolve(gridObj);
                } else {
                  console.log("功能扩展暂无数据");
                  resolve(null);
                }
              } 
              
              catch (error) {
                console.error("功能扩展报错:", error);
                reject(error);
              }
            });
  
          });
        }
  
        // 执行所有异步请求
        async function fetchAllData() {
          try {
            let results = await Promise.all(parsedData.map(fetchData));
            gridArr = results.filter(Boolean); // 过滤掉 null
            // 调用新增表体行数据的函数
            if (gridArr.length > 0) {
              WLMX.addRows(gridArr);
            } else {
              console.warn("未能添加任何数据");
            }
            // 清除 LocalStorage 数据
            localStorage.removeItem("selectedUSourceData");
            console.log("LocalStorage 已清除");
          } catch (error) {
            console.error("获取数据出错:", error);
          }
        }
        fetchAllData(); // 调用异步方法
      } else {
        console.log("LocalStorage 中没有数据");
      }
  
      YQGYSdtoolbar1.insert({
        id: "add",
        text: "供应商引入",
        iconCls: "icon-New",
      });
      useClick(async function ({ args }) {
        if (mstform.getItem("u_wlxl").getValue().length > 0) {
          console.log(mstform.getItem("u_wlxl").getValue());
          YQGYSadd();
        } else {
          tabPanel[0].click();
          $NG.alert("请先选择物料明细表");
        }
      }, "add");
      useDataIndexChange(({ args }) => {
        getItemdataByPhid(args[0]);
      }, "u_item_no");
  
      //////////////////////////////////////////////////mstform//////////////////////////////////////////////////
  
      const toolbar_supply = $NG.getCmpApi("toolbar_p_form_supply");
      const toolbar_pbzb = $NG.getCmpApi("toolbar_p_form_pbzb");
      const toolbar_zbwj = $NG.getCmpApi("toolbar_p_form_zbwj");
      const toolbar_section = $NG.getCmpApi("toolbar_p_form_section");
      const toolbars = [
        { toolbar: toolbar_supply, items: ["imp"] },
        { toolbar: toolbar_pbzb, items: ["imp"] },
        { toolbar: toolbar_zbwj, items: ["imp"] },
        { toolbar: toolbar_section, items: ["imp"] },
      ];
      toolbars.forEach(({ toolbar, items }) => {
        if (toolbar) {
          items.forEach((item) => toolbar.getItem(item)?.setHidden()); //setHidden：隐藏按钮，setDisabled：禁用按钮
        }
      });
  
      useBeforeClick(async function ({ args }) {
        let flag = true;
        if (mstform.getItem("u_zbfs").getValue() == "1289") {
          console.log(true, "11111111");
          console.log(YQGYS.getRows().length, "11111111");
          if (YQGYS.getRows().length) {
          } else {
            flag = false;
            $NG.alert("您的招标方式是邀标,需要填写邀请供应商明细表");
          }
        }
        //保存钩子
        console.log(WLMX.getRows(), "WLMX.getRows();");
        // let flagYxsll = mstform.getItem("u_yxsll").getValue();
        // console.log(flagYxsll, "flagYxsll");
        let rows = WLMX.getRows();
        let total = 0;
        rows.forEach((element) => {
          if (element.u_ncg_qty) {
            total += parseFloat(element.u_ncg_qty);
          }
        });
  
        // if (total > 0 || flagYxsll == "1") {
        // } else {
        //     flag = false;
        //     $NG.alert("物料数量小于0");
        // }
        let rows2 = PBZB.getRows();
        let total2 = 0;
  
        rows2.forEach((element) => {
          console.log(element, "element");
          if (element.u_bzf) {
            total2 += parseFloat(element.u_bzf);
          }
        });
        // if (total2 == 100) {
        // } else {
        // 	$NG.alert("指标数量总和数量应等于100");
        // 	flag = false;
        // }
  
        return flag; // 取消向下执行
      }, "save");
  
      //////////////////////////////////////////////////mstform//////////////////////////////////////////////////
  
      $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zbhy.u_ycdjlx?.setProps({
          hidden: true,
        });
      });
  
      //选物料带出单位等
      function getItemdataByPhid(item) {
        const phid = item.u_item_no;
        $NG.execServer("getItemdataByPhid", { phid }, (res) => {
          if (res.count == 0) return;
          const data = JSON.parse(res.data)[0].extendObjects;
          console.log(data);
  
          item.u_item_name = data.itemname;
          item.u_unit = data.msunit_phid;
          item.u_unit_EXName = data.msunit_name;
          item.u_spec = data.spec;
          item.u_wlfl = data.res_bs_phid;
          item.u_wlfl_EXName = data.res_bs_name;
          WLMX.refreshView();
        });
      }
      useValuesChange(({ args }) => {
        console.log(args[0]);
        const cno = args[0].u_zblx.origin.c_no;
        $NG.updateState((updater) => {
          updater.data.p_form_zbhy.setProps({
            u_ycdjlx: cno,
          });
        });
      }, "p_form_zbhy.u_zblx");
  
      if (mstform.getItem("u_is_jnbzj").getValue() == 1) {
        $NG.updateUI((updater) => {
          const fields = ["u_tender_bond", "u_zffs", "u_skdw", "u_kh_bank"];
          fields.forEach((field) => {
            updater.fieldSetForm.p_form_zbhy[field].setProps({
              required: true,
            });
          });
        });
      }
      useValuesChange(({ args }) => {
        console.log(args[0].u_is_jnbzj.value);
        if (args[0].u_is_jnbzj.value == 1) {
          $NG.updateUI((updater) => {
            const fields = ["u_tender_bond", "u_zffs", "u_skdw", "u_kh_bank"];
            fields.forEach((field) => {
              updater.fieldSetForm.p_form_zbhy[field].setProps({
                required: true,
                disabled: false,
              });
            });
          });
        } else {
          $NG.updateUI(function (updater, state) {
            const fields = ["u_tender_bond", "u_zffs", "u_skdw", "u_kh_bank"];
            console.log(updater);
  
            fields.forEach((field) => {
              updater.fieldSetForm.p_form_zbhy[field].setProps({
                required: false, //required是否必输
                disabled: true,
              });
            });
          });
        }
      }, "p_form_zbhy.u_is_jnbzj");
      useValuesChange(({ args }) => {
        console.log(args[0].u_kzjbj);
        console.log();
  
        if (args[0].u_kzjbj == 1) {
          $NG.updateUI((updater) => {
            const fields = ["u_kz_prcvat", "u_kz_tax", "u_kz_amtvat"];
            fields.forEach((field) => {
              updater.editGrid.p_form_wlmx[field].setProps({
                required: true, //必输
              });
            });
          });
          $NG.updateUI((updater) => {
            const fields = ["u_ck_prcvat", "u_ck_amtvat"];
            fields.forEach((field) => {
              updater.editGrid.p_form_wlmx[field].setProps({
                required: false, //必输
              });
            });
          });
        } else if (args[0].u_kzjbj == 2) {
          $NG.updateUI((updater) => {
            const fields = ["u_ck_prcvat", "u_ck_amtvat"];
            fields.forEach((field) => {
              updater.editGrid.p_form_wlmx[field].setProps({
                required: true,
              });
            });
          });
          $NG.updateUI((updater) => {
            const fields = ["u_kz_prcvat", "u_kz_tax", "u_kz_amtvat"];
            fields.forEach((field) => {
              updater.editGrid.p_form_wlmx[field].setProps({
                required: false,
              });
            });
          });
        }
      }, "p_form_zbhy.u_kzjbj");
  
      // const u_zbdw = mstform.getItem("u_zbdw"); //招标单位 (当前默认登录人组织)
      let user = $NG.getUser(); //登陆人信息
      if (page.oType == "add") {
        $NG.updateState((updater) => {
          updater.data.p_form_zbhy.setProps({
            u_sqperson: {
              label: user.userName,
              value: user.userID,
            },
          });
        });
      }
  
      var tabPanel = document.getElementsByClassName("ant-tabs-tab"); //获取所有tab页元素
      var tabP = document.getElementsByClassName("ant-tabs-nav-list")[0]; //获取所有tab页元素
      if (mstform.getValues().wf_flag == 4) {
        tabPanel[1].style.display = "none"; // 隐藏
      }
      if (page.oType == "edit") {
        JTpl();
        $NG.updateUI((updater, state) => {
          if (page.Id) {
            updater.editGrid.p_form_wlmx.u_section.setProps((e) => ({
              ...e,
              editor: {
                ...e.editor,
                required: true,
                clientSqlFilter: { phid: page.Id },
              },
            }));
          }
        });
  
        function Fun() {
          const pb90Response = mstform.getItem("u_is_dbdzb").getValue();
          if (pb90Response == 0 && tabPanel[4].innerText == "标段") {
            tabPanel[4].style.display = "none"; // 隐藏
          }
          if (pb90Response == 1 && tabPanel[4].innerText == "标段") {
            tabPanel[4].style.display = "none"; // 隐藏
            setTimeout(() => {
              tabP.insertBefore(tabPanel[4], tabP.firstChild);
              setTimeout(() => {
                tabPanel[0].style.display = "block"; // 显示
                if (page.oType == "edit") {
                  $NG.updateUI((updater) => {
                    const fields = ["u_section"];
                    fields.forEach((field) => {
                      updater.editGrid.p_form_wlmx[field].setProps({
                        hidden: false, //隐藏
                        // required: true, //必输
                        // disabled: true, //只读
                      });
                    });
                  });
                }
              }, 200);
            }, 200);
          }
        }
        Fun();
      }
      if (page.oType == "add") {
        // 初始化隐藏标段
        $NG.updateUI((updater) => {
          const fields = ["u_section"];
          fields.forEach((field) => {
            updater.editGrid.p_form_wlmx[field].setProps({
              hidden: true, //隐藏
              // required: true, //必输
              // disabled: true, //只读
            });
          });
        });
  
        try {
          mstform.getItem("u_isbm").setValue(1);
        } catch (error) {}
        {
          /**
           *@default: 初始化
           */
          JTpl();
          tabPanel[4].style.animation = "none";
          tabPanel[4].style.display = "none";
          if ($NG.getCmpApi("p_form_zbhy")) {
            BD.clearRows();
            getPtInfoByPhid();
            if (user) {
              //带出默认用户登录的组织
              $NG.execServer("GetHrInfo", { id: user.userID }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                //帮助字段赋值
                $NG.updateState((updater) => {
                  // 帮助字段
                  updater.data.p_form_zbhy.setProps({
                    u_zbdw: {
                      value: datas.org_phid,
                      label: datas.org_oname,
                    },
                  });
                });
              });
            }
          }
          mstform.getItem("u_fill_dt").setValue(new Date());
        }
      }
  
      /**
       *@license:检测工程项目带出项目信息
       */
      useValuesChange(({ args }) => {
        getPtInfoByPhid();
        console.log("是否触发phid.pc");
      }, "p_form_zbhy.phid_pc");
      /**
       *@license:监听物料小类变化
       */
      useValuesChange(({ args }) => {
        JTpl();
      }, "p_form_zbhy.u_wlxl");
      /**
       *@license:监听定价项目编号
       */
      useValuesChange(({ args }) => {
        // var mstform = $NG.getCmpApi("p_form_zbhy"); //获取表头数据
        console.log(args[0].u_djsqdh.origin, "u_djsqdh");
        const {
          bill_dt = null, //定价申请时间
          bill_name = null, //定价申请名称
          bill_no = null, //定价清单编号
          pc = null, //项目名称
          phid = null, //定价申请单主键
          phid_pc = null, //项目主键
          u_bus_no = null, //商机编号
          u_sj_name = null, //商机名称
        } = args[0].u_djsqdh.origin;
  
        mstform.getItem("phid_pc").setValue({ label: pc, value: phid_pc });
        //   if (pc) {
        $NG.updateState((updater) => {
          updater.data.p_form_zbhy.setProps({
            u_sjh: u_bus_no,
            u_sjmc: u_sj_name,
          });
        });
        //   }
      }, "p_form_zbhy.u_djsqdh");
  
      function validateDates() {
        const { u_end_dt, u_start_dt, u_isbm } = mstform.getValues();
        if (!u_isbm) {
          return true;
        }
        if (u_end_dt && u_start_dt) {
          return !u_isbm || (!isNaN(new Date(u_start_dt).getTime()) && !isNaN(new Date(u_end_dt).getTime()) && new Date(u_end_dt) > new Date(u_start_dt));
        } else {
          return true;
        }
      }
      // let input = "8570000000000004,8570000000000008";
      // let output = input.replace(/,/g, "|");
      let reqTimeLock = 0;
      let timeMax = 0;
      //去重
      function removeDuplicatesByKeys(arr) {
        const uniqueMap = new Map();
        for (const obj of arr) {
          // 生成一个由 ItemName、PhidResbs 和 PhidMsunit 组合而成的唯一键
          const key = `${obj.ItemName}-${obj.Spec}-${obj.PhidMsunit}`;
          if (!uniqueMap.has(key)) {
            // 如果该键还未存在于 Map 中，则将对象存入
            uniqueMap.set(key, obj);
          }
        }
        // 将 Map 中的值（即去重后的对象）提取到一个新数组中
        return Array.from(uniqueMap.values());
      }
      useBeforeClick(({ args }) => {
        $NG.message("正在匹配 0.1% 请耐心等待~~~");
        window.stertNum = 0;
        window.endNum = 0;
        window._list = [];
        reqTimeLock = setInterval(() => {
          if (window.stertNum == window.endNum) {
            //可以请求了
            $NG.message(`正在匹配 ${(stertNum / (WLMX.getRows().length * 2.5)).toFixed(4) * 100}% 请耐心等待~~~`);
            const list = removeDuplicatesByKeys(window._list);
            console.log(`数据准备就绪：`, list);
            if (list.length == 0) {
              $NG.alert("匹配完成！ 100%");
            } else {
              getWlRequest(list);
            }
            clearInterval(reqTimeLock);
          } else {
            window.endNum = window.stertNum;
          }
        }, 1000);
        matchingMaterial();
      }, "user_match");
      //匹配物料主请求
      async function getWlRequest(list) {
        const response = await fetch("http://nginx.clouddev.hisense.com/sd/interior/createResourceFileSync", {
          method: "POST",
          headers: {
            "Content-Type": "application/json", // 设置请求头
          },
          body: JSON.stringify(list),
        });
        const res = await response.json();
        console.log(`请求数据`, res);
        if (res.IsOk) {
          //新增成功
          matchingMaterial(); //重新匹配
          [1, 2, 3].forEach((item) => {
            $NG.message(`正在重新匹配，请勿操作等待提示完成！！！%`);
          });
          timeMax = setTimeout(() => {
            $NG.alert("匹配超时！！！");
          }, 1000 * 90);
          $NG.alert("匹配完成！ 100%");
          clearTimeout(timeMax);
        } else {
          if (res.data == "批量新增失败，入参为空！") {
            $NG.alert("匹配完成，入参为空！");
          } else {
            $NG.alert("匹配错误！");
          }
        }
      }
  
      //匹配物料
      function matchingMaterial() {
        const d1arr = WLMX.getRows();
        d1arr.forEach((item, index) => {
          if (!(String(item.u_item_name) || "").trim() || !(String(item.u_unit) || "").trim() || !(String(item.u_spec) || "").trim() || !(String(item.u_item_sub) || "").trim()) {
          } else {
            $NG.execServer(
              "getItemDataByName",
              {
                itemname: `'${item.u_item_name}'`,
                spec: `'${item.u_spec}'`,
                msunit: `'${item.u_unit}'`,
              },
              function (res) {
                console.log(item.u_item_name, item.u_spec, item.u_unit, res);
                window.stertNum += 1;
                if (res.count > 0) {
                  const data = JSON.parse(res.data)[0].extendObjects;
                  console.log("编码查询", data, data.itemno);
                  item.u_item_no_EXName = data.itemno;
                  item.u_item_no = data.phid;
                  WLMX.refreshView();
                } else {
                  $NG.execServer("getResBsByphid", { phid: item.u_item_sub }, (res2) => {
                    window.stertNum += 1;
                    const _data = JSON.parse(res2.data)[0].extendObjects;
                    window._list.push({
                      ItemName: item.u_item_name,
                      PhidResbs: item.u_item_sub,
                      PhidMsunit: item.u_unit,
                      Spec: item.u_spec,
                      ResBsCode: item.u_item_sub, // 假设 ResBsCode 是固定值，需根据实际情况调整
                      ResourceType: _data.resource_type, // 假设资源类型是固定的
                    });
                  });
                }
              }
            );
          }
        });
      }
  
      function YQGYSadd() {
        $NG.external
          .openNGHelp({
            type: "NGMultipleHelp", //NGMultipleHelp
            helpId: "fc3_supply_copy", //帮助id
            valueField: "phid",
            labelField: "u_milestone_name", //显示字段
            // clientSqlFilter: `REGEXP_LIKE(res, '(^|)857000000000000(8|4)(|$)')`
            clientSqlFilter: `REGEXP_LIKE(res, '(^|)${mstform.getItem("u_wlxl").getValue().join("|")}(|$)')`,
          })
          .then((data) => {
            //根据字段名称新增引入每一行
            console.log(data, "data111111");
            try {
              if (Array.isArray(data) && data.length > 0) {
                var gridArr = [];
                for (var i = 0; i < data.length; i++) {
                  console.log(data[i], "row1数据");
                  var gridObj = {};
  
                  gridObj.u_dwbh = data[i].origin.compno; //单位编号
                  gridObj.u_dwmc = data[i].origin.phid; //单位phid
                  gridObj.u_dwmc_EXName = data[i].origin.compname; //单位名称;
  
                  gridArr.push(gridObj);
                }
  
                console.log("planadd gridArr:");
                console.log(gridArr);
                YQGYS.addRows(gridArr);
                YQGYS.refreshView();
              } else {
                console.error("返回的数据无效或为空:", data);
              }
            } catch (error) {
              console.error("处理数据时出错:", error);
            }
          })
          .catch((error) => {
            console.error("打开NGHelp时发生错误:", error);
          });
      }
      /**
       *@license:监听 报名结束时间
       */
  
      useValuesChange(({ args }) => {
        if (validateDates()) {
        } else {
          mstform.getItem("u_end_dt").setValue(null);
          $NG.alert("报名结束时间不能小于报名开始时间");
        }
      }, "p_form_zbhy.u_end_dt");
      /**
       *@license:监听 报名开始时间
       */
      useValuesChange(({ args }) => {
        if (validateDates()) {
        } else {
          mstform.getItem("u_start_dt").setValue(null);
          $NG.alert("报名开始时间不能大于报名结束时间");
        }
      }, "p_form_zbhy.u_start_dt");
      /**
       *@license:监听 是否报名
       */
      useValuesChange(({ args }) => {
        if (validateDates()) {
        } else {
          mstform.getItem("u_start_dt").setValue(null);
          $NG.alert("报名开始时间不能大于报名结束时间");
        }
      }, "p_form_zbhy.u_isbm");
      /**
                 *@license:招标方式
                如果是邀标，则标段不可选同时邀请供应商必选1289
                 */
      useValuesChange(({ args }) => {}, "p_form_zbhy.u_zbfs");
  
      var u_kb_dt = mstform.getItem("u_kb_dt"); //开始投标时间
      var u_tbjz_dt = mstform.getItem("u_tbjz_dt"); //投标截至时间
      var u_bs_end_xz = mstform.getItem("u_bs_end_xz"); //标书下载截至时间
      var u_bs_start_xz = mstform.getItem("u_bs_start_xz"); //标书开始下载截至时间
      /**
       *@license:检测开标时间
       */
      useValuesChange(async ({ args }) => {
        const pb90Response = await new Promise((resolve, reject) => {
          resolve(mstform.getItem("u_is_dbdzb").getValue());
        });
        if (pb90Response == 1 && tabPanel[4].innerText == "标段") {
          // 加强校验预防暴力点击
          if (page.oType == "edit") {
            $NG.updateUI((updater) => {
              const fields = ["u_section"];
              fields.forEach((field) => {
                updater.editGrid.p_form_wlmx[field].setProps({
                  hidden: false, //隐藏
                  // required: true, //必输
                  // disabled: true, //只读
                });
              });
            });
          }
          tabPanel[4].style.display = "block";
          tabP.insertBefore(tabPanel[4], tabP.firstChild); // 插入到 tab 列表的开头
        } else if (pb90Response == 0 && tabPanel[0].innerText == "标段") {
          if (page.oType == "edit") {
            $NG.updateUI((updater) => {
              const fields = ["u_section"];
              fields.forEach((field) => {
                updater.editGrid.p_form_wlmx[field].setProps({
                  hidden: false, //隐藏
                  // required: true, //必输
                  // disabled: true, //只读
                });
              });
            });
          }
          tabPanel[0].style.display = "none";
          tabP.appendChild(tabPanel[0]); // 插入到 tab 列表的末尾
          tabPanel[0].click();
          BD.clearRows();
        }
      }, "p_form_zbhy.u_is_dbdzb");
      /**
       *@license:检测开标时间
       */
      useValuesChange(({ args }) => {
        //开始标时间
        let flag = checkDate(u_kb_dt.getValue());
        if (!flag && u_kb_dt.getValue()) {
          $NG.alert("开标时间不能小于今天");
          u_kb_dt.setValue("");
        }
        if (u_tbjz_dt.getValue() && u_kb_dt.getValue()) {
          if (!BidDateVerification()) {
            $NG.alert("投标截至时间不能大于或等于开标时间");
            u_kb_dt.setValue("");
          }
        }
      }, "p_form_zbhy.u_kb_dt");
  
      /**
       *@license:检测投标截止时间
       */
      useValuesChange(({ args }) => {
        //投标截至时间
        let flag = checkDate(u_tbjz_dt.getValue());
        if (!flag && u_tbjz_dt.getValue()) {
          $NG.alert("投标截至时间不能小于今天");
          u_tbjz_dt.setValue("");
        }
        if (u_tbjz_dt.getValue() && u_kb_dt.getValue()) {
          if (!BidDateVerification()) {
            $NG.alert("投标截至时间不能大于或等于开标时间");
            u_tbjz_dt.setValue("");
          }
        }
      }, "p_form_zbhy.u_tbjz_dt");
      /**
       *@license:检测标书开始下载时间
       */
      useValuesChange(({ args }) => {
        //标书开始时间
        let flag = checkDate(u_bs_start_xz.getValue(), true);
        if (!flag && u_bs_start_xz.getValue()) {
          $NG.alert("表述开始时间不能小于今天");
          u_bs_start_xz.setValue("");
        }
  
        if (u_bs_end_xz.getValue() && u_bs_start_xz.getValue()) {
          if (!DataTimeValidation()) {
            $NG.alert("标书下载载止时间小于标书下载开始时间!");
            u_bs_start_xz.setValue("");
          }
        }
      }, "p_form_zbhy.u_bs_start_xz");
      /**
       *@license:检测标书下载截止时间
       */
      useValuesChange(({ args }) => {
        //标书下载截至时间
        let flag = checkDate(u_bs_end_xz.getValue());
        if (!flag && u_bs_end_xz.getValue()) {
          $NG.alert("标书下载截至时间不能小于今天");
          u_bs_end_xz.setValue("");
        }
  
        if (u_bs_end_xz.getValue() && u_bs_start_xz.getValue()) {
          if (!DataTimeValidation()) {
            $NG.alert("标书下载载止时间小于标书下载开始时间!");
            u_bs_end_xz.setValue("");
          }
        }
      }, "p_form_zbhy.u_bs_end_xz");
  
      /**
       *@function:带出项目信息
       */
      function getPtInfoByPhid() {
        // console.log("进入getPtInfoByPhid", mstform.getItem("phid_pc").getValue());
        // if (mstform.getItem("phid_pc").getValue()) {
        //     $NG.execServer("projectSjbm", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        //         console.log(res, "进入结果");
        //         const datas = JSON.parse(res.data)[0].extendObjects;
        //         $NG.updateState((updater) => {
        //             updater.data.p_form_zbhy.setProps({
        //                 u_sjh: datas.user_sjbm,
        //                 u_sjmc: datas.user_sjmc,
        //             });
        //         });
        //     });
        // }
      }
  
      function BidDateVerification() {
        //投标截至时间两时间校验
        return new Date(u_kb_dt.getValue()).setHours(0, 0, 0, 0) > new Date(u_tbjz_dt.getValue()).setHours(0, 0, 0, 0);
      }
      function DataTimeValidation() {
        //标书下载时间两时间校验
        return new Date(u_bs_end_xz.getValue()).setHours(0, 0, 0, 0) > new Date(u_bs_start_xz.getValue()).setHours(0, 0, 0, 0);
      }
      //汇总
      function reduceNum(arr) {
        let total_amt = arr.reduce((value, item) => {
          value += (Number(item.u_ncg_qty) || 0) * (Number(item.u_kz_prcvat) || 0);
          return value;
        }, 0);
        $NG.updateState((updater) => {
          updater.data.p_form_zbhy.setProps({
            u_zbkzj: total_amt,
          });
        });
      }
  
      useUpdateRows(({ args }) => {
        console.log("useUpdateRows");
        // 先判断有没有选择项目
        WLMXUpdateRows(args[0]);
        reduceNum(args[0]);
      }, "p_form_wlmx");
  
      function WLMXUpdateRows(rows) {
        let total = 0;
        rows.forEach((item) => {
          if (!item.u_yztj_prc) return;
  
          total += Number(item.u_yztj_prc);
        });
        mstform.getItem("u_zbkzj").setValue(total);
        if (rows.length < 1) {
          mstform.getItem("u_wlxl").setValue(null);
        }
        rows.forEach((item) => {
          console.log(item, "result获取id列表item");
          //设置控制含税金额
          item.u_kz_amtvat = (Number(item.u_kz_prcvat) || 0) * (Number(item.u_ncg_qty) || 0) * (1 + (Number(item.u_kz_tax) || 0));
          item.u_ck_amtvat = (Number(item.u_ck_prcvat) || 0) * (Number(item.u_ncg_qty) || 0);
          if (!item.u_item_no) return; //如果不存在phid_itemdata则不执行
          $NG.execServer("search_phiditemdata", { phid: item.u_item_no }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas, "search_phiditemdata");
            item.itemid = datas.ps_resbase_phid;
            item.itemno = datas.itemno;
            item.itemname = datas.itemname;
            item.spec = datas.spec;
            item.msunit = datas.msunit_phid;
            item.msunit_EXName = datas.msunit_name;
            item.u_wlfl = datas.res_bs_phid;
            item.u_wlfl_EXName = datas.res_bs_name;
            const merged = [];
            // 用于记录已经处理过的 u_item_no 和 itemno 组合
            const processed = new Set();
  
            rows.forEach((item) => {
              const key = `${item.u_item_no}-${item.itemno}`;
              console.log(key, merged, 111111);
  
              if (!processed.has(key)) {
                merged.push(item);
                processed.add(key);
              }
            });
            if (merged.length > 0) {
              const result = merged.map((item) => ({ value: item.u_wlfl, label: item.u_wlfl_EXName }));
              console.log(result, "result获取id列表,");
              const uniqueData = [];
              const seen = new Set();
  
              result.forEach((item) => {
                const key = `${item.value}-${item.label}`;
                if (!seen.has(key)) {
                  uniqueData.push(item);
                  seen.add(key);
                }
              });
              console.log("供应商uniqueData", uniqueData);
              mstform.getItem("u_wlxl").setValue(uniqueData);
              WLMX.refreshView();
            }
            // 提取所有元素的 u_wlfl_EXName 并拼接成字符串
            WLMX.refreshView();
          });
          if (!item.u_section) {
            //如果没有默认选择不区分标段
            item.u_section = 1;
            item.u_section_EXName = "不区分标段";
          }
        });
        WLMX.refreshView();
      }
      function JTpl() {
        try {
          WLMXUpdateRows(WLMX.getRows());
        } catch (error) {}
  
        // WLMX.getRows().forEach((item, index) => {
  
        // })
        if (mstform.getItem("u_wlxl").getValue()) {
          $NG.updateUI((updater, state) => {
            updater.editGrid.p_form_supply.u_pl.setProps((e) => ({
              ...e,
              editor: {
                ...e.editor,
                required: true,
                // clientSqlFilter: { phid: 8570000000000004, },
                clientSqlFilter: `phid in (${mstform.getItem("u_wlxl").getValue().join(",")})`,
              },
            }));
          });
        }
      }
  
      //////////////////////////////////////////////////p_form_supply//////////////////////////////////////////////////
  
      $NG.updateUI((updater) => {
        const fields = ["u_gys_phid"];
        fields.forEach((field) => {
          updater.editGrid.p_form_supply[field]?.setProps({
            hidden: true, //隐藏
            // required: true, //必输
            // disabled: true, //只读
          });
        });
      });
      useUpdateRows(({ args }) => {
        const rows = args[0];
        if (mstform.getItem("u_wlxl").getValue()) {
        } else {
          $NG.alert("请先在物料明细表添加本次物料");
        }
        rows.forEach((item) => {
          console.log(item, "item获取供应商rowdata");
  
          if (!item.u_dwmc) return; //如果不存在单位名称就不执行
          $NG.execServer(
            "getSuClass",
            {
              phid: item.u_dwmc,
            },
            function (res) {
              console.log(res, "getSuClass");
              try {
                const getSuClassData = JSON.parse(res.data)[0].extendObjects;
                console.log(getSuClassData, "getSuClassData");
                item.u_gyssx = getSuClassData.user_gyssx; //供应商类型
                // item.u_dwbh = getSuClassData.compno;
                if (getSuClassData.user_status !== null) {
                  item.u_gyszt = ["正常", "淘汰", "禁用", "冻结"][getSuClassData.user_status - 1];
                }
                item.u_org = getSuClassData.phid_org;
                item.u_org_EXName = getSuClassData.oname;
                //如果有默认选中的类型就是业主推荐 新增的是否
                // item.u_gyszt = getSuClassData.fsaleflg;
              } catch (error) {
                item.u_gyslx = "";
                item.u_dwbh = "";
                item.u_org = "";
                item.u_org_EXName = "";
                // item.u_gyszt = "";
              }
              YQGYS.refreshView();
            }
          );
          if (!item.u_pl) return;
          // 8570000000000004;
          y;
        });
      }, "p_form_supply");
      useDataIndexChange(({ args }) => {
        console.log("u_dwmc", args);
        let row = args[0];
  
        row.u_gys_phid = args[1].update.originValue.PhId;
  
        //赋值操作计算数量*单价=金额
        YQGYS.updateRow(row);
      }, "u_dwmc");
      useDataIndexChange(({ args }) => {
        let row = args[0];
        console.log(row, "11111???row");
      }, "u_pl");
    },
    function (editPage, { useAction }) {
      //编辑页面逻辑
    },
    function (listPage, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange, useBeforeClick }) {}
  );
  
  function checkDate(inputDateStr, toLock = false) {
    // 获取今天的日期并设置时间为00:00:00
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 将今天的时间部分归零
  
    // 将传入的日期转换为 Date 对象
    const inputDate = new Date(inputDateStr);
    inputDate.setHours(0, 0, 0, 0); // 将输入日期的时间部分归零
  
    // 如果传入的日期无效，返回 false
    if (isNaN(inputDate)) {
      return false;
    }
    console.log(inputDate, "inputDate");
    console.log(today, "today");
  
    // 比较日期部分（不考虑时间）
    if (toLock) {
      return inputDate >= today;
    } else {
      return inputDate > today;
    }
  }
  